package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.WarnStrategy;
import com.mingqijia.gassafety.db.entity.WarningRecord;
import com.mingqijia.gassafety.db.entity.vo.DisposeRecordResponseVO;
import com.mingqijia.gassafety.db.entity.vo.DisposeRecordVO;
import com.mingqijia.gassafety.db.entity.vo.WarningRecodeVO;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.dto.CallTaskDTO;
import com.mingqijia.gassafety.webserver.request.DisposeRecordRequest;
import com.mingqijia.gassafety.webserver.request.WarningRecordDetailRequest;
import com.mingqijia.gassafety.webserver.request.WarningRecordInfoRequest;
import com.mingqijia.gassafety.webserver.request.WarningRecordListRequest;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.ContactsService;
import com.mingqijia.gassafety.webserver.service.WarningRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_ASST;
import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 预警记录 服务实现类
 * </p>
 *
 * @author zhangfei
 * @since 2022-03-08
 */
@Service
@Slf4j
public class WarningRecordServiceImpl extends ServiceImpl<WarningRecordMapper, WarningRecord> implements WarningRecordService {


    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    WarningRecordMapper recordMapper;

    @Autowired
    ConsumerMapper consumerMapper;

    @Autowired
    WarnStrategyMapper warnStrategyMapper;

    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    ContactsService contactsService;

    @Autowired
    ConfigureHolder holder;
    @Autowired
    HeaderUtil headerUtil;
    @Autowired
    WarningRecordMapper warningRecordMapper;
    @Autowired
    XFCallServiceImpl xfCallService;

    @Autowired
    CompanyService companyService;

    public  void updateRecordStatus(String imei, String taskIdentificationCode,int status ) {
        WarningRecord warningRecord = new WarningRecord();
//        warningRecord.setIMEI(imei);
        warningRecord.setTaskIdentificationCode(taskIdentificationCode);
        warningRecord.setEndTime(new Date());
        warningRecord.setStatus(status);
        QueryWrapper<WarningRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or()
                .eq(WarningRecord::getTaskIdentificationCode,taskIdentificationCode);
        warningRecordMapper.update(warningRecord,queryWrapper);
    }


    public void updateRecordStatusByImei(String imei) {
        log.info("updateRecordStatusByImei-param:{}",imei);
        long time = new Date().getTime();
        QueryWrapper<WarningRecord> query = new QueryWrapper<>();
        query.lambda().or().eq(WarningRecord::getNotifyFrom,0)
                .eq(WarningRecord::getStatus,0)
        .likeRight(WarningRecord::getIMEI,imei);
        List<WarningRecord> warningRecords = warningRecordMapper.selectList(query);
        log.info("updateRecordStatusByImei-warningRecords:{}",JSONObject.toJSON(warningRecords));
        if (!CollectionUtils.isEmpty(warningRecords)){
            warningRecords.forEach(warningRecord ->{
                log.info("updateRecordStatusByImei-warningRecord:{}",JSONObject.toJSON(warningRecord));
                long time1 = warningRecord.getCreatedAt().getTime();
                log.info("execute-time1:{},time:{}",time1,time);
                if (time-time1>=3600000) {
                    log.info("execute-time-time1:{}",time-time1);
                    warningRecord.setId(warningRecord.getId());
                    warningRecord.setEndTime(warningRecord.getStartTime());
                    warningRecord.setStatus(2);
                    warningRecordMapper.updateById(warningRecord);
                }
            });
        }
    }
    @Override
    public PageUtil<WarningRecordResponse> getList(WarningRecordListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        PageUtil<WarningRecordResponse> recordPageUtil = new PageUtil<>();

        //通知对象名,查客户表获得集合
        List<Integer> consumerIds = null;
        if (StringUtil.isNotEmpty(request.getNoticeObject()) || StringUtil.isNotEmpty(request.getNoticeSubsCode())
                || StringUtil.isNotEmpty(request.getNoticeCustName()) || StringUtil.isNotEmpty(request.getNoticeMemberId())
                || StringUtil.isNotEmpty(request.getNoticeContactPhone())) {
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda()    //查询条件发生变化
                    .like(StringUtil.isNotEmpty(request.getNoticeCustName()), Consumer::getCustName, request.getNoticeCustName())
                    .like(StringUtil.isNotEmpty(request.getNoticeSubsCode()), Consumer::getSubsCode, request.getNoticeSubsCode())
                    .like(StringUtil.isNotEmpty(request.getNoticeObject()), Consumer::getName, request.getNoticeObject())
                    .eq(Consumer::getSpId, spId)
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .like(StringUtil.isNotEmpty(request.getNoticeContactPhone()), Consumer::getPhone, request.getNoticeContactPhone())
                    .like(StringUtil.isNotEmpty(request.getNoticeMemberId()), Consumer::getMemberId, request.getNoticeMemberId());
            List<Consumer> consumerList = consumerMapper.selectList(consumerQueryWrapper);
            if (CollectionUtil.isEmpty(consumerList)) {
                return recordPageUtil;
            }
            consumerIds = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
        }
        List<Long> strategyIds = null;
        if (StringUtil.isNotEmpty(request.getStrategyName())) {
            //规则名,查规则表获得集合
            QueryWrapper<WarnStrategy> strategyQueryWrapper = new QueryWrapper<>();
            strategyQueryWrapper.lambda()
                    .like(StringUtil.isNotEmpty(request.getStrategyName()), WarnStrategy::getRuleName, request.getStrategyName())
                    .eq(WarnStrategy::getSpId, spId)
                    .eq(WarnStrategy::getIsDeleted, Constants.IS_DELETED_FALSE);
            List<WarnStrategy> warnStrategyList = warnStrategyMapper.selectList(strategyQueryWrapper);
            if (CollectionUtil.isEmpty(warnStrategyList)) {
                return null;
            }
            strategyIds = warnStrategyList.stream().map(WarnStrategy::getId).collect(Collectors.toList());
        }
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        log.info("sql查询开始");
        //根据条件,聚合查询得到列表
        List<WarningRecodeVO> warningRecordList = recordMapper.selectCountList(request.getStartTimeBeginning(),
                request.getStartTimeEnd(), request.getWarningStartTimeBeginning(), request.getWarningStartTimeEnd(), consumerIds, strategyIds,
                request.getType(), request.getStatus(), spId, request.getImei());
        log.info("sql查询结束");

        //判断设备类型
        List<DictionaryItemRespDTO> dictionaryList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        ArrayList<String> imeiList = new ArrayList<>();
        for (WarningRecodeVO recodeVO : warningRecordList) {
            // 上级设备类型是 控制器的
            if (Constants.GAS_ALARM_CONTROLLER.equals(recodeVO.getEquipmentType())) {
                // 点探IMEI
                imeiList.add(recodeVO.getIMEI());
            }
        }
        //当存在父级设备是控制器时,也就是点型探测器
        //List<Dtu> dtuList = null;
        Map<String, Dtu> dtuMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(imeiList)) {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda()
                    .in(Dtu::getIMEI, imeiList)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
            if (!CollectionUtils.isEmpty(dtuList)) {
                dtuMap = dtuList.stream().collect(Collectors.toMap(Dtu::getIMEI, Dtu -> Dtu, (a1, a2) -> a1));
            }
        }
        //处理数据,得到实际上报设备的设备信息
        for (WarningRecodeVO vo : warningRecordList) {
            //如果有点型探测器
            if (dtuMap.containsKey(vo.getIMEI()) && dtuMap.get(vo.getIMEI()) != null) {
                Dtu dtu = dtuMap.get(vo.getIMEI());
                vo.setSupIMEI(vo.getIMEI());
                vo.setEquipmentName(dtu.getName());
                vo.setEquipmentType(dtu.getEquipmentType());
            }
            DictionaryItemRespDTO dict = dictionaryList.stream().filter(a -> a.getValue().equals(
                    vo.getEquipmentType())).collect(Collectors.toList()).get(0);
            vo.setEquipmentTypeName(dict.getName());
        }
        List<WarningRecordResponse> recordResponseList = BeanConvertUtils.convertListTo(warningRecordList, WarningRecordResponse::new);
        recordPageUtil.setPage(request.getPage());
        recordPageUtil.setTotal(page.getTotal());
        recordPageUtil.setPageSize(request.getPageSize());
        recordPageUtil.setList(recordResponseList);
        return recordPageUtil;
    }

    @Override
    public WarningRecordDetailResponse recordDetailInfo(WarningRecordDetailRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Integer templateType = headerUtil.getTemplateType();

        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumer = consumerMapper.selectOne(consumerWrapper);

        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }

        //获取联系人列表
        QueryWrapper<Contacts> contactsWrapper = new QueryWrapper<>();
        contactsWrapper.lambda().eq(Contacts::getConsumerId, request.getConsumerId())
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Contacts::getSpId, spId);
        List<Contacts> contactsList = contactsService.list(contactsWrapper);
        List<ContactsResponse> contactsResponseList = BeanConvertUtils.convertListTo(contactsList, ContactsResponse::new);
        //级别名称
        for (ContactsResponse contactsResponse : contactsResponseList) {
            if (contactsResponse.getLevel() != null) {
                DictionaryItemRespDTO communicationModeDict = holder.getDictionaryByKey(
                        Constants.CONTACT_LEVEL).stream().filter(a -> a.getValue().equals(
                        contactsResponse.getLevel().toString())).collect(Collectors.toList()).get(0);
                contactsResponse.setLevelName(communicationModeDict.getName());
            }
        }
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu dtu = dtuMapper.selectOne(dtuQueryWrapper);


        if (dtu == null || consumer == null) {
            throw new BizException("该设备或客户已不存在.");
        }
        WarningRecordDetailResponse detailResponse = new WarningRecordDetailResponse();
        BeanUtil.copyProperties(dtu, detailResponse);
        BeanUtil.copyProperties(consumer, detailResponse);
        detailResponse.setPositionLat(dtu.getPositionLat());
        detailResponse.setPositionLon(dtu.getPositionLon());
        detailResponse.setConsumerName(consumer.getName());
        detailResponse.setEquipmentName(dtu.getName());
        detailResponse.setContactsResponseList(contactsResponseList);
        if (StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
            detailResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
        } else {
            if (companyNameMap.containsKey(consumer.getSpId())) {
                detailResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
            }
        }

        //如果为模板二 设备的工单信息
        if (templateType == BIND_CHANNEL_ASST) {
            QueryWrapper<DtuBindingOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DtuBindingOrder::getDeviceId, request.getImei())
                    .eq(DtuBindingOrder::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(DtuBindingOrder::getSpId, spId);
            List<DtuBindingOrder> dtuBindingOrderList = dtuBindingOrderMapper.selectList(queryWrapper);
            if (CollectionUtil.isEmpty(dtuBindingOrderList)) {
                throw new BizException("该设备未查询到对应工单.");
            }

            DtuBindingOrder order = dtuBindingOrderList.get(0);
            if (order.getConsumerId().equals(request.getConsumerId())){
                detailResponse.setContactName(order.getCustName());
                detailResponse.setContactPhone(order.getPhone());
                detailResponse.setContactAddress(order.getAddress());
            }

        }
        DictionaryItemRespDTO dict = holder.getDictionaryByKey(EquipmentType.DICT_CODE).stream()
                .filter(a -> a.getValue().equals(dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
        detailResponse.setEquipmentTypeName(dict.getName());
        DictionaryItemRespDTO industryType = holder.getIndustryTypeZJ().stream()
                .filter(a -> a.getValue().equals(consumer.getIndustryType())).collect(Collectors.toList()).get(0);
        detailResponse.setIndustryTypeName(industryType.getName());
        BeanUtil.copyProperties(request, detailResponse);

        return detailResponse;
    }

    @Override
    public PageUtil<WarningRecordInfoResponse> recordDetailList(WarningRecordInfoRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        QueryWrapper<WarningRecord> warningRecordQueryWrapper = new QueryWrapper<>();
        warningRecordQueryWrapper.lambda().eq(WarningRecord::getTaskIdentificationCode, request.getTaskIdentificationCode())
                .eq(WarningRecord::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(WarningRecord::getSpId, spId)
                .eq(WarningRecord::getNotifyFrom, 0); //消息来源: 报警策略;
        if (request.getSendType() == null) {
            warningRecordQueryWrapper.lambda().in(WarningRecord::getSendType, 1,2,3,4);
        }
        Page<WarningRecord> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<WarningRecord> warningRecordList = this.list(warningRecordQueryWrapper);
        //取出所以id查询当前id是否有子级
        List<Long> ids = warningRecordList.stream().map(WarningRecord::getId).collect(Collectors.toList());
        Map<Long, List<WarningRecord>> warningMap;
        if (!CollectionUtils.isEmpty(ids)) {
            LambdaQueryWrapper<WarningRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(WarningRecord::getParentId, ids)
                    .eq(WarningRecord::getIsDeleted, Constants.IS_DELETED_FALSE);
            List<WarningRecord> warningRecords = this.list(lambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(warningRecords)) {
                warningMap = warningRecords.stream().collect(Collectors.groupingBy(WarningRecord::getParentId));
            } else {
                warningMap = new HashMap<>();
            }
        } else {
            warningMap = new HashMap<>();
        }
        List<WarningRecordInfoResponse> infoResponseList = BeanConvertUtils.convertListTo(warningRecordList, WarningRecordInfoResponse::new);
        for (WarningRecordInfoResponse response : infoResponseList) {
            response.setConcentration(response.getConcentration() + " %LEL");
            //取出所以id查询当前id是否有子级
            if (warningMap.containsKey(response.getId())) {
                List<WarningRecordInfoResponse> responseList = new ArrayList<>();
                List<WarningRecord> warningRecords = warningMap.get(response.getId());
                for (WarningRecord warningRecord : warningRecords) {
                    WarningRecordInfoResponse infoResponse = new WarningRecordInfoResponse();
                    BeanUtils.copyProperties(warningRecord, infoResponse);
                    infoResponse.setConcentration(warningRecord.getConcentration() + " %LEL");
                    responseList.add(infoResponse);
                }
                response.setChildren(responseList);
            }
        }
        PageUtil<WarningRecordInfoResponse> pageUtil = new PageUtil<>();
        pageUtil.setList(infoResponseList);
        pageUtil.setTotal(page.getTotal());
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        return pageUtil;
    }

    /**
     * 存储外呼记录
     *
     * @param data
     * @param dtuInfos
     * @param phones
     * @param warningAlarm
     * @return
     */
    @Override
    public boolean saveCallList(JSONArray data, Map<String, Object> dtuInfos, List<String> phones,
                                WarningAlarm warningAlarm, String spId, Map<String, Integer> objectTypeMap,
                                String operatorBy,String robotContent) {

        try {
            Integer value = 0;
            int report = 0;
            Date date = null;
            long snowflakeId = 0L;
            int sendType = 0;
            int sendResult = 0;
            snowflakeId = Long.parseLong(warningAlarm.getId() + "");
            value = warningAlarm.getConcentration();
            date = new Date();
            sendType = 4;
            for (int i = 0; i < phones.size(); i++) {
                String content = (StringUtil.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES:robotContent)
                        .replace("#name#", dtuInfos.get("name")+"")
                        .replace("#address#", dtuInfos.get("addressCopy")+"")
                        .replace("#phone#",dtuInfos.get("paramValue")+"")
                        .replace("#factoryName#",dtuInfos.get("factoryName")+"");

                saveWarningRecord(spId, dtuInfos.get("iMEI") + "", value, report, dtuInfos.get("Id") + "",
                        0, 0, date, sendType, snowflakeId, sendResult, content, dtuInfos.get("iMEI") + "",
                        data.get(i) + "", phones.get(i) + "", objectTypeMap.get(phones.get(i)), "",operatorBy);

            }
        } catch (Exception e) {
            log.error("saveCallList-error:{}",e);
            return false;
        }
        return true;
    }

    @Override
    public PageUtil<DisposeRecordResponse> getRecordList(DisposeRecordRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        ArrayList<DisposeRecordResponse> resultList = new ArrayList<>();
        DisposeRecordVO vo = new DisposeRecordVO();
        BeanUtil.copyProperties(request, vo);
        vo.setSpId(spId);
        List<DisposeRecordResponseVO> list = this.baseMapper.getList(vo);
        //被真正处理的，有着拨出记录的数据
        List<DisposeRecordResponse> sendLists = list.stream()
                .filter(item -> item.getPushPhone() != null).map(item -> {
            DisposeRecordResponse response = new DisposeRecordResponse();
            BeanUtil.copyProperties(item, response);
            return response;
        }).collect(Collectors.toList());
        resultList.addAll(sendLists);

        //处理状态为 忽略 的数据
        List<DisposeRecordResponse> disposedList = list.stream()
                .filter(item -> item.getDisposeStatus() == 1).map(item -> {
                    DisposeRecordResponse response = new DisposeRecordResponse();
                    BeanUtil.copyProperties(item, response);
                    response.setOperatorBy(item.getOperator());
                    return response;
                }).collect(Collectors.toList());
        resultList.addAll(disposedList);

        //取出所以id查询当前id是否有子级
        List<Long> ids = list.stream().filter(item -> item.getId() != null).map(DisposeRecordResponseVO::getId).collect(Collectors.toList());
        Map<Long, List<WarningRecord>> warningMap;
        if (!CollectionUtils.isEmpty(ids)) {
            LambdaQueryWrapper<WarningRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(WarningRecord::getParentId, ids)
                    .eq(WarningRecord::getIsDeleted, Constants.IS_DELETED_FALSE);
            List<WarningRecord> warningRecords = this.list(lambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(warningRecords)) {
                warningMap = warningRecords.stream().collect(Collectors.groupingBy(WarningRecord::getParentId));
            } else {
                warningMap = new HashMap<>();
            }
        } else {
            warningMap = new HashMap<>();
        }

        //未被真正处理的记录填充手机号码
        for (DisposeRecordResponseVO item : list) {
            for (DisposeRecordResponse sendVo : sendLists) {
                if (item.getPushPhone() == null
                        && sendVo.getDisposeTime().equals(item.getDisposeTime())){
                    DisposeRecordResponse disposeRecord = new DisposeRecordResponse();
                    BeanUtils.copyProperties(item, disposeRecord);
                    disposeRecord.setNotifyObjType(sendVo.getNotifyObjType());
                    disposeRecord.setSendResult(sendVo.getSendResult());
                    disposeRecord.setSendTime(sendVo.getSendTime());
                    disposeRecord.setPushPhone(sendVo.getPushPhone());
                    disposeRecord.setRemark(sendVo.getRemark());
                    resultList.add(disposeRecord);
                }
            }
        }

        for (DisposeRecordResponse disposeRecordResponse : resultList) {
            if (warningMap.containsKey(disposeRecordResponse.getId())) {
                List<WarningRecord> warningRecords = warningMap.get(disposeRecordResponse.getId());
                List<DisposeRecordResponse> responseList = new ArrayList<>();
                for (WarningRecord warningRecord : warningRecords) {
                    DisposeRecordResponse infoResponse = new DisposeRecordResponse();
                    BeanUtils.copyProperties(disposeRecordResponse, infoResponse);
                    infoResponse.setPushPhone(warningRecord.getPushPhone());
                    infoResponse.setSendResult(warningRecord.getSendResult());
                    infoResponse.setSendTime(warningRecord.getCreatedAt());
                    infoResponse.setDisposeStatus(3);
                    responseList.add(infoResponse);
                    disposeRecordResponse.setChildren(responseList);
                }
            }
        }
        //排序
        List<DisposeRecordResponse> responseList = resultList.stream()
                .filter(item -> {
                    if(request.getNotifyObjType() != null){
                        return request.getNotifyObjType().equals(item.getNotifyObjType());
                    }
                    if(!StringUtil.isEmpty(request.getPushPhone())){
                        return request.getPushPhone().equals(item.getPushPhone());
                    }
                    return true;
                })
                .sorted(Comparator.comparing(DisposeRecordResponse::getWarningStartTime).reversed())
                .sorted(Comparator.comparing(DisposeRecordResponse::getDisposeTime).reversed())
            .collect(Collectors.toList());

        int total = responseList.size();
        int fromIndex = (request.getPage()-1) * request.getPageSize();
        // 结束索引
        int toIndex = fromIndex + request.getPageSize();
        // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
        if(toIndex > total){
            toIndex = total;
        }
        if(fromIndex <= total){
            List<DisposeRecordResponse> subList = responseList.subList(fromIndex, toIndex);
            return new PageUtil<>(request.getPage(),
                    request.getPageSize(),  total, subList);
        }else{
            return new PageUtil<>(request.getPage(),
                    request.getPageSize(),  0 , null);
        }
    }

    @Override
    public Object createTask(CallTaskDTO request) {
        JSONObject jsonObject = request.getId()==null?xfCallService.tackPoolAdd(request):
                xfCallService.taskPoolUpdate(request);
        log.info("createTask-jsonObject:{}",jsonObject);
        return jsonObject;
    }
    @Override
    public Object createApp( String appName,String appKey,String appSecret,Integer id) {
        Object jsonObject =id==null?xfCallService.appCreate(appName,appKey,appSecret):
                xfCallService.appUpdate(appName,id);
        log.info("createApp-jsonObject:{}",jsonObject);
        return jsonObject;
    }

    //存储报警记录
    private void saveWarningRecord(String spId, String iMEI,
                                   Integer value, int report, String con, Object strategyId,
                                   Integer level, Date date, int sendType, long snowflakeId, int sendResult,
                                   String content, String supIMEI,
                                   String receiptCode, String telephone, int type, String info,String operatorBy) {
        WarningRecord warningRecord = new WarningRecord();
        warningRecord.setConsumerId(con);
        warningRecord.setStartTime(date);
        warningRecord.setWarningStartTime(date);
        warningRecord.setTriggerRuleId(strategyId + "");
        warningRecord.setIMEI(iMEI);
        warningRecord.setTaskIdentificationCode(snowflakeId + "");
        warningRecord.setConcentration(value + "");
        warningRecord.setType(report);
        warningRecord.setSendType(sendType);
        if (StringUtils.isNotEmpty(con) && StringUtils.isNotEmpty(telephone)) {
            List<Contacts> contacts = contactsService.selectConsumerId(Integer.valueOf(con));
            if (!CollectionUtils.isEmpty(contacts)) {
                Map<String, Integer> integerMap = contacts.stream().collect(Collectors.toMap(Contacts::getTelephone, Contacts::getLevel, (t1, t2) -> t1));
                level = integerMap.get(telephone);
            }
        }
        warningRecord.setObjLevel(level);
        warningRecord.setSpId(spId);
        warningRecord.setSendResult(2);
        warningRecord.setContent(content);
        warningRecord.setReceiptCode(receiptCode);
        warningRecord.setNotifyObjInfo(info);
        warningRecord.setNotifyObjType(type);
        warningRecord.setPushPhone(telephone);
        warningRecord.setSupIMEI(supIMEI);
        warningRecord.setNotifyFrom(2);
        warningRecord.setOperatorBy(operatorBy);
        log.info("saveWarningRecord:{}", JSONObject.toJSONString(warningRecord));
        recordMapper.insert(warningRecord);
    }

    @Override
    public int CountRecord(String IMEI,String spId) {
        QueryWrapper<WarningRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.lambda()
                .eq(WarningRecord::getSpId,spId)
                .eq(WarningRecord::getIMEI,IMEI)
                .eq(WarningRecord::getSendType,2)
                .eq(WarningRecord::getNotifyFrom,0)
                .eq(BaseEntity::getIsDeleted,0);
        return recordMapper.selectCount(recordQueryWrapper);
    }

}
